package tld.test.menu.challenges
{
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFormat;
	
	import tld.test.interpreter.IContext;
	import tld.test.menu.Challenge;
	import tld.test.menu.Console;
	import tld.test.menu.IChallenge;
	
	[Event(name="win", type="tld.test.menu.challenges.ChallengeEvent")]
	
	[Event(name="loose", type="tld.test.menu.challenges.ChallengeEvent")]
	
	public class Quiz extends Sprite implements IChallenge
	{
		private const _challenge:Challenge = new Challenge();
		
		private var _winner:int;
		
		private var _questions:Array;
		
		private const _fields:Array = [];
		
		private const _format:TextFormat = new TextFormat("_sans"); 
		
		private var _console:Console;
		
		public function Quiz()
		{
			super();
			this._challenge.put("reset", this.reset);
			this._challenge.put("answer", this.answer);
		}
		
		public function setConsole(console:Console):void
		{
			this._console = console;
		}
		
		public function challenge():IContext
		{
			return this._challenge;
		}
		
		public function help():String
		{
			return <![CDATA[;;; This is Quiz program

; You are tested on basic calculus skills:
; call (answer #) to select the correct answer.
; Advanced users can try `reset' option. `reset' requires an argument
; of type int - the index of the correct answer, the rest of the arguments
; are taken to be the questions.

; call (unload) to unload this challenge.]]>.toString();
		}
		
		public function defaults():String
		{
			return <![CDATA[
			(reset 2 "1 > 2" "3 + 5 = 8" 
                   "7 / 3 = 4" "2 * 1/2 < 2")]]>.toString();
		}
		
		public function context():IContext
		{
			return this._challenge;
		}
		
		public function reset(winner:int, ...questions):void
		{
			this._winner = winner;
			this._questions = questions.concat();
			this.draw();
		}
		
		public function answer(index:int):void
		{
			var type:String = 
				this._winner == index ? 
				ChallengeEvent.WIN : ChallengeEvent.LOOSE;
			super.dispatchEvent(new ChallengeEvent(type));
		}
		
		private function draw():void
		{
			while (super.numChildren) super.removeChildAt(0);
			this._fields.splice(0, this._fields.length);
			for each (var question:String in this._questions)
				this._fields.push(this.addField(question));
		}
		
		private function addField(text:String):TextField
		{
			var field:TextField = new TextField();
			field.autoSize = TextFieldAutoSize.LEFT;
			field.defaultTextFormat = this._format;
			field.text = text;
			field.selectable = false;
			field.addEventListener(
				MouseEvent.CLICK, this.clickHandler);
			field.y = super.height;
			return super.addChild(field) as TextField;
		}
		
		private function clickHandler(event:MouseEvent):void
		{
			if (this._console)
				this._console.run("(answer " + 
					this._fields.indexOf(event.currentTarget) + ")"); 
			else this.answer(this._fields.indexOf(event.currentTarget));
			
		}
	}
}